<template>
  <div>
    <button @click="handleAdd('input')">添加输入框</button>
    <button @click="handleAdd('date')">添加日期</button>
    <button @click="handleAdd('time')">添加时间</button>
    <button @click="handleAdd('radio')">添加按钮</button>
    <button @click="handleAdd('checkbox')">添加选中</button>
    <button @click="handleAdd('img', 'jia')">添加甲方签名</button>
    <button @click="handleAdd('img', 'yi')">添加乙方签名</button>
    <button @click="getValue">获取value</button>
    <editor
      style="width: 100%; height: 500px"
      api-key="442y290atvj552xm6dniegkiwtw0su51stkals22c0eyjhj0"
      :init="initData"
      v-model="data"
      @input="changeValue"
      ref="editor"
    />
    <!-- <textarea id="mytextarea">Hello, World! <input></textarea> -->
  </div>
</template>

<script>
import Editor from '@tinymce/tinymce-vue'
// import tinymce from "tinymce";
export default {
  name: 'app',
  data() {
    return {
      data: '',
      idList: [],
      form: {},
      x: 100,
      y: 200,
      initData: {
        height: 500,
        toolbar: 'pagebreak',
        language_url: '/tinymce/langs/zh_CN.js',
        language: 'zh_CN',
        skin_url: '/tinymce/skins/ui/oxide-dark',
        paste_data_images: true,
        // browser_spellcheck: true,
        plugins: [
          'advlist autolink  lists link imagetools image charmap print preview anchor colorpicker textcolor contextmenu',
          'searchreplace visualblocks code fullscreen',
          'insertdatetime media table paste code help wordcount autoresize,pagebreak',
        ],
        toolbar:
          'undo redo | formatselect | bold italic backcolor | \
            alignleft aligncenter alignright alignjustify | \
            bullist numlist outdent indent |imagetools image media | removeformat | help',
      },
    }
  },
  components: {
    editor: Editor,
  },
  methods: {
    changeValue(val) {
      this.data = val
    },
    changePosition() {},
    insertImg(editor, { path, id }) {
      editor.undoManager.transact(() => {
        editor.focus()
        editor.selection.setContent(
          editor.dom.createHTML('img', {
            src: path,
            id,
            name: 'jia',
            style: 'width:100px;50px;transition:1s',
          }),
        )
      })
    },
    insertImg2(editor, { path, id }) {
      const that = this
      editor.undoManager.transact(() => {
        editor.focus()
        editor.selection.setContent(
          editor.dom.createHTML('img', {
            src: path,
            id,
            name: 'yi',
            style: 'width:100px;50px;transition:0s;position:relative;',
          }),
        )

        let dragging = false
        let position = null
        // 1、鼠标按下
        editor.dom.doc.getElementById(id).onmousedown = function (e) {
          // 事件对象
          // var x = prompt("水平位置px(默认100)", 100);
          // var y = prompt("垂直位置px(默认100)", 100);
          // editor.dom.doc.getElementById(id).style.top = x + "px";
          // editor.dom.doc.getElementById(id).style.left = y + "px";
          dragging = true // 正在移动

          position = [e.clientX, e.clientY]
        }
        editor.dom.doc.getElementById(id).onmousemove = function (e) {
          if (dragging === false) {
            return
          }
          const x = e.clientX
          const y = e.clientY
          console.log(x, y)
          const deltaX = x - position[0]
          const deltaY = y - position[1]
          const left = parseInt(editor.dom.doc.getElementById(id).style.left || 0)
          const top = parseInt(editor.dom.doc.getElementById(id).style.top || 0)
          editor.dom.doc.getElementById(id).style.left = `${left + deltaX}px`
          editor.dom.doc.getElementById(id).style.top = `${top + deltaY}px`
          position = [x, y]
        }

        editor.dom.doc.getElementById(id).onmouseup = function () {
          dragging = false
          // editor.dom.doc.getElementById(id).onmousemove = null; //鼠标松开取消移动时候的效果
        }
      })
    },
    insertInput(editor, type, id) {
      const that = this
      editor.undoManager.transact(() => {
        editor.focus()

        if (type == 'checked') {
          editor.selection.setContent(editor.dom.createHTML('input', { type, id, name: id }))
        }
        if (type == 'img') {
          editor.selection.setContent(editor.dom.createHTML('input', { type, id, name: id }))
        }
        if (type == 'time' || type == 'date') {
          editor.selection.setContent(editor.dom.createHTML('input', { type, id, name: id }))
        }

        if (type == 'radio') {
          editor.selection.setContent(editor.dom.createHTML('input', { type, id, name: id, value: 0 }))
          editor.selection.setContent(editor.dom.createHTML('input', { type, id: id + 1, name: id, value: 1 }))
          editor.dom.doc.querySelector(`#${id}`).addEventListener('click', e => {
            editor.dom.doc.querySelector(`#${id}`).setAttribute('checked', true)
            that.form[id] = editor.dom.doc.querySelector(`#${id}`).getAttribute('value')
            console.log(that.form, 'from')
          })
          editor.dom.doc.querySelector(`#${id}${1}`).addEventListener('click', e => {
            editor.dom.doc.querySelector(`#${id + 1}`).setAttribute('checked', true)
            that.form[id] = editor.dom.doc.querySelector(`#${id + 1}`).getAttribute('value')
            console.log(that.form, 'from')
          })
        }
        if (type == 'input') {
          editor.dom.createHTML('input', { type, id, name: id })
          editor.dom.doc.querySelector(`#${id}`).addEventListener('change', e => {
            editor.dom.doc.querySelector(`#${id}`).setAttribute('value', e.target.value)
            that.form[id] = e.target.value

            console.log(that.form, 'from')
          })
        }
      })
    },
    getValue(editor) {
      editor = this.$refs.editor.editor
      editor.undoManager.transact(() => {
        editor.selection.dom.get('key0').setAttribute('checked', true)
      })
    },
    handleAdd(type, name) {
      if (type == 'input') {
        const id = `key${this.idList.length}`
        this.idList.push(id)
        this.insertInput(this.$refs.editor.editor, 'input', id)
      }
      if (type == 'date') {
        const id = `key${this.idList.length}`
        this.idList.push(id)
        this.insertInput(this.$refs.editor.editor, 'date', id)
      }
      if (type == 'time') {
        const id = `key${this.idList.length}`
        this.idList.push(id)
        this.insertInput(this.$refs.editor.editor, 'time', id)
      }
      if (type == 'radio') {
        const id = `key${this.idList.length}`
        this.idList.push(id)

        this.insertInput(this.$refs.editor.editor, 'radio', id)
        // this.insertInput(this.$refs.editor.editor, "radio", id);
        // this.insertWord(this.$refs.editor.editor);
        // this.insertInput(this.$refs.editor.editor, "radio", id);
        // this.data =
        //   this.data +
        //   `<input value='' type='radio' id="${id}" name="${id}" checked="checked"/>是<input value='' type='radio' id="${id}" name="${id}" />否`;
      }

      if (type == 'checkbox') {
        const id = `key${this.idList.length}`
        this.idList.push(id)
        this.insertInput(this.$refs.editor.editor, 'checkbox', id)
      }
      if (type == 'img') {
        const id = `key${this.idList.length}`
        this.idList.push(id)
        if (name == 'jia') {
          const path = 'https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fimg.tukuppt.com%2Fpng_preview%2F00%2F16%2F86%2Fs5CBMjGe36.jpg%21%2Ffw%2F780&refer=http%3A%2F%2Fimg.tukuppt.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1660614018&t=97fe009e4aef40837a1ac1d177b0570e'
          this.insertImg(this.$refs.editor.editor, { path, id })
        }
        if (name == 'yi') {
          const path = 'https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fbpic.51yuansu.com%2Fpic3%2Fcover%2F00%2F74%2F50%2F58b828216ff6e_610.jpg&refer=http%3A%2F%2Fbpic.51yuansu.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1660614018&t=4d65c551c9ff2380671eed6d3ea81b96'
          this.insertImg2(this.$refs.editor.editor, { path, id })
        }
      }

      // this.data = this.data.replace("<p>", "").replace("</p>", "");
      // console.log(this.data, "debugger");
    },
  },
  mounted() {
    const form = {
      key0: '123',
      key1: '0',
      key2: '1',
    };
    [{ key: 'key0', value: '123', type: 'input' }]
  },
}
</script>
<style>
.pagebreak {
  display: block;
  clear: both !important;
  cursor: move !important;
  height: 100% !important;
  margin: 0;
  background: url("' + me.options.UEDITOR_HOME_URL + '/themes/default/images/ph-jt-divide.png") ' + ' no-repeat center;
  height: 16px;
  border: none 0;
}
</style>
